package net.lainiao.zhihu.reptitle;

import net.lainiao.zhihu.common.Common;
import net.lainiao.zhihu.model.Qutupage;
import net.lainiao.zhihu.model.Qutupagegif;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/1/19.
 */
public class QutuCommon {
    public static List<Qutupage> getQutupages(String url) throws InterruptedException, SAXException, IOException {
        Document document=HtmlCommon.getDocument(url);
        Elements elements=document.select(".box");
        List<Qutupage> list=new ArrayList<Qutupage>();
        for(Element element:elements){
            Qutupage qutupage=new Qutupage();
            Elements links=element.select("a");
            if(links.size()>1){
                Element element1=links.first();
                String href=element1.attr("href");
                if(href.indexOf("http://tu.duowan.com/g")>-1){
                    href=href.replace("http://tu.duowan.com/g","");
                    href=href.replace("/","").replace(".html","");
                    int a=Integer.parseInt(href,16);
                    href="http://tu.duowan.com/scroll/"+a+".html";
                    qutupage.setUrl(href);
                    element1=element1.child(0);
                    qutupage.setImg(element1.attr("src"));
                    Element element2=links.get(1);
                    String name=element2.text();
                    name=new String(name.getBytes("ISO-8859-1"),"UTF-8");
                    qutupage.setName(name);
                    list.add(qutupage);
                    qutupage.setStatus(0);
                    qutupage.setId(Common.getNewUUID());
                }
            }
        }
        return list;
    }

    public static List<Qutupagegif> getQutupagegifs(String url) throws InterruptedException, SAXException, IOException {
        Document document=HtmlCommon.getDocument(url);
        List<Qutupagegif> qutupagegifs=new ArrayList<Qutupagegif>();
        Elements elements=document.select(".pic-box");
        for(Element element:elements){
            Qutupagegif qutupagegif=new Qutupagegif();
            String name=element.select("p").first().text();
            name=new String(name.getBytes("ISO-8859-1"),"UTF-8");
            String src=element.select("img").first().attr("src");
            qutupagegif.setId(Common.getNewUUID());
            qutupagegif.setName(name);
            qutupagegif.setUrl(src);
            qutupagegifs.add(qutupagegif);
        }
        return qutupagegifs;
    }
}
